/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 *
 */
var threeSumClosest = function (nums, target) {
  nums.sort((a, b) => a - b);
  let spance = null; //距离差
  let spanceSum = 0;
  // let start = 0;
  // let center = 1;
  // let end = 2;
  // for (; end < nums.length; end++) {
  //   let sum = nums[start] + nums[center] + nums[end];
  //   if (spance == null) {
  //     spance = Math.abs(sum - target);
  //     spanceSum = sum;
  //   }
  //   if (Math.abs(sum - target) < spance) {
  //     spance = Math.abs(sum - target);
  //     spanceSum = sum;
  //   } else if (Math.abs(sum - target) > spance) {
  //     end--;
  //     break;
  //   } else if (Math.abs(sum - target) == 0) {
  //     return sum;
  //   }
  // }

  // for (; center < end; center++) {
  //   let sum = nums[start] + nums[center] + nums[end];

  //   if (Math.abs(sum - target) < spance) {
  //     spance = Math.abs(sum - target);
  //     spanceSum = sum;
  //   } else if (Math.abs(sum - target) > spance) {
  //     center--;
  //     break;
  //   } else if (Math.abs(sum - target) == 0) {
  //     return sum;
  //   }
  // }

  // for (; start < center; start++) {
  //   let sum = nums[start] + nums[center] + nums[end];

  //   if (Math.abs(sum - target) < spance) {
  //     spance = Math.abs(sum - target);
  //     spanceSum = sum;
  //   } else if (Math.abs(sum - target) > spance) {
  //     start--;
  //     break;
  //   } else if (Math.abs(sum - target) == 0) {
  //     return sum;
  //   }
  // }

  for (let i = 0; i < nums.length; i++) {
    let start = i + 1;
    // let end = i + 2;
    // debugger;
    while (start < end && end < nums.length) {
      let sum = nums[i] + nums[start] + nums[end];
      if (spance == null) {
        spanceSum = sum;
        spance = Math.abs(sum - target);
      }
      if (Math.abs(sum - target) < spance) {
        spance = Math.abs(sum - target);
        spanceSum = sum;
        end++;
      } else if (Math.abs(sum - target) > spance) {
        // 停止end 索引 不能向右移了  后面的只会越来越大
        // return sum;
        end--;
        break;
      } else if (Math.abs(sum - target) == 0) {
        return sum;
      }
    }
  }

  return spanceSum;
};

var nums = [-12, -11, -3, 0, 1, 2, 5, 6, 9];
// var nums = [1, 2, 3, 5, 12, 15];
var target = 16;
let result = threeSumClosest(nums, target);
console.log(result);
